﻿using System;
using System.Windows;
using System.Windows.Media.Animation;
using System.Windows.Media;

namespace Store.WP7.Framework.Animations
{
    public static class Animator
    {
        public static void AddTimeline(this Storyboard storyboard, Timeline timeline, DependencyObject target, object propertyPath, TimeSpan duration)
        {
            timeline.FillBehavior = FillBehavior.HoldEnd;
            timeline.Duration = duration;
            Storyboard.SetTarget(timeline, target);
            Storyboard.SetTargetProperty(timeline, new PropertyPath(propertyPath));
            storyboard.Children.Add(timeline);
        }

        public static DoubleAnimation AddEasingDoubleAnimation(double from, double to, double duration,
            IEasingFunction easing, object propertyPath, DependencyObject target)
        {
            var db = new DoubleAnimation();
            db.To = to;
            db.From = from;
            db.EasingFunction = easing;
            db.Duration = TimeSpan.FromSeconds(duration);
            Storyboard.SetTarget(db, target);
            Storyboard.SetTargetProperty(db, new PropertyPath(propertyPath));
            return db;
        }

        public static DoubleAnimation AddDoubleAnimation(double from, double to, double duration,
          object targetProperty, DependencyObject target)
        {
            var db = new DoubleAnimation();
            db.To = to;
            db.From = from;
            db.EasingFunction = new SineEase();
            db.Duration = TimeSpan.FromSeconds(duration);
            Storyboard.SetTarget(db, target);
            Storyboard.SetTargetProperty(db, new PropertyPath(targetProperty));
            return db;
        }
    }

    public static class ExtensionMethods
    {
        /// <summary>
        /// Calls TransformToVisual on the specified element for the specified visual, suppressing the ArgumentException that can occur in some cases.
        /// </summary>
        public static Point GetRelativePosition(this UIElement element, UIElement other)
        {
            GeneralTransform transform;
            try
            {
                transform = element.TransformToVisual(other);
            }
            catch (ArgumentException)
            {
                // Not perfect, but better than throwing an exception
                transform = new TranslateTransform();
            }

            return transform.Transform(new Point(0, 0));
        }
    }
}
